import { eachStr } from '@library/utils/replace/replace';

export function parsingStr(str: string, data: object | undefined | null) {
  const _data = data || {};

  const each = (str: string, _data: object) => {
    return eachStr(str, (k: string) => {
      let value = _data[k!];
     
      if (k.includes('.')) {
        const arr = k.split('.');
  
        value = _data[arr[0]];
  
        for (let i = 1; i < arr.length; i++) {
          value = value?.[arr[i]];
        }
      }
  
      return value
    })
  }

  if(Array.isArray(_data)) {
    const arr: any[] = [];

    _data.forEach(item => {
      arr.push(each(`{{${str}}}`, item));
    })

    return arr.filter(item => {
      return item && item !== 'null' && item !== 'undefined'
    }).join(',')
  }else {
    let _str = str.includes('{{') ? each(str, _data) : each(`{{${str}}}`, _data);
    
    if(_str === 'undefined' || _str === 'null') return '';
    return _str;
  }
}